package com.pablito.webapp.action;

import java.util.List;

import com.opensymphony.xwork2.Preparable;
import com.pablito.dao.SearchException;
import com.pablito.model.Cliente;
import com.pablito.service.GenericManager;

public class ClienteAction extends BaseAction implements Preparable {
    private GenericManager<Cliente, Long> clienteManager;
    private List clientes;
    private Cliente cliente;
    private Long id;
    private String query;

    public void setClienteManager(GenericManager<Cliente, Long> clienteManager) {
        this.clienteManager = clienteManager;
    }

    public List getClientes() {
        return clientes;
    }

    /**
     * Grab the entity from the database before populating with request parameters
     */
    public void prepare() {
        if (getRequest().getMethod().equalsIgnoreCase("post")) {
            // prevent failures on new
            String clienteId = getRequest().getParameter("cliente.id");
            if (clienteId != null && !clienteId.equals("")) {
                cliente = clienteManager.get(new Long(clienteId));
            }
        }
    }

    public void setQ(String q) {
        this.query = q;
    }

    public String list() {
        try {
            clientes = clienteManager.getAll();
        } catch (SearchException se) {
            addActionError(se.getMessage());
            clientes = clienteManager.getAll();
        }
        return SUCCESS;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public Cliente getCliente() {
        return cliente;
    }

    public void setCliente(Cliente cliente) {
        this.cliente = cliente;
    }

    public String delete() {
        clienteManager.remove(cliente.getId());
        saveMessage(getText("cliente.deleted"));

        return SUCCESS;
    }

    public String edit() {
        if (id != null) {
            cliente = clienteManager.get(id);
        } else {
            cliente = new Cliente();
        }

        return SUCCESS;
    }

    public String save() throws Exception {
        if (cancel != null) {
            return "cancel";
        }

        if (delete != null) {
            return delete();
        }

        boolean isNew = (cliente.getId() == null);

        clienteManager.save(cliente);

        String key = (isNew) ? "cliente.added" : "cliente.updated";
        saveMessage(getText(key));

        if (!isNew) {
            return INPUT;
        } else {
            return SUCCESS;
        }
    }
}